package com.codefish.framework.spring.core.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 反射相关工具类
 *
 * @author <a href='https://gitee.com/hzf2281'>codefish</a>
 * @version 1.0.0
 * @since 2022/10/15 上午 09:46
 */
public abstract class ReflectionUtils {
    public static final String EQUALS_METHOD_NAME = "equals";
    public static final String HASHCODE_METHOD_NAME = "hashCode";

    /**
     * 判断某个方法是否为equals方法
     *
     * @param method 目标方法
     * @return 如果是，返回true
     */
    public static boolean isEqualsMethod(Method method) {
        if (method == null || !EQUALS_METHOD_NAME.equals(method.getName())) {
            return false;
        }
        Class<?>[] parameterTypes = method.getParameterTypes();
        if (parameterTypes.length != 1 || parameterTypes[0] != Object.class) {
            return false;
        }

        return true;
    }

    /**
     * 判断某个方法是否为hashcode方法
     *
     * @param method 目标方法
     * @return 如果是，返回true
     */
    public static boolean isHashCodeMethod(Method method) {
        if (method == null || !HASHCODE_METHOD_NAME.equals(method.getName())) {
            return false;
        }

        if (method.getParameterTypes().length > 0) {
            return false;
        }
        return true;
    }

    /**
     * 遍历目标class对象中的所有域，并执行回调方法
     *
     * @param clazz          目标class
     * @param doWithCallback 回调方法
     */
    public static void doWithLocalFields(Class<?> clazz, FieldFunction doWithCallback) {
        if (clazz == null) {
            return;
        }
        for (Field field : clazz.getDeclaredFields()) {
            try {
                doWithCallback.doWith(field);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }



    public interface FieldFunction {
        /**
         * 处理目标field
         *
         * @param field 目标field
         * @throws IllegalAccessException
         */
        void doWith(Field field) throws IllegalAccessException;
    }

}
